<?php

namespace App\Http\Middleware;

use App\Common\ApiErrorCode;
use App\Common\JwtAuth;
use App\Exceptions\ApiException;
use App\Http\Response\ResponseJson;
use Closure;

class JwtMiddleware
{
    use ResponseJson;

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 获取到客户端提交 token
        $token = $request->input('token');
        if ($token) {
            $jwtAuth = JwtAuth::getInstance();
            $jwtAuth->setToken($token);
            if ($jwtAuth->validate() && $jwtAuth->verify()) {
                return $next($request);
            } else {
                throw new \Exception(ApiErrorCode::ERROR_TOKEN[0],ApiErrorCode::ERROR_TOKEN[1]);
            }
        } else {
            throw new \Exception(ApiErrorCode::ERROR_PARAMS[0],ApiErrorCode::ERROR_PARAMS[1]);
        }
    }
}
